import { memo, useEffect, useState } from 'react'
import { Pagination } from 'antd'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'

type propTypes = {
  total: number
}

const ListPage = memo(({ total }: propTypes) => {
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)

  const [searchParams] = useSearchParams()

  useEffect(() => {
    const getPage = Number(searchParams.get('page')) || 1
    const getPageSize = Number(searchParams.get('pageSize')) || 5

    setPage(getPage)
    setPageSize(getPageSize)
  }, [searchParams])

  const nav = useNavigate()
  const { pathname } = useLocation()
  const handleChange = (page: number, pageSize: number) => {
    searchParams.set('page', String(page))
    searchParams.set('pageSize', String(pageSize))

    nav({
      pathname,
      search: searchParams.toString(),
    })
  }

  return (
    <Pagination
      showTotal={total => `共 ${total} 条数据`}
      current={page}
      pageSize={pageSize}
      showSizeChanger
      pageSizeOptions={['5', '10', '20']}
      total={total}
      onChange={handleChange}
    />
  )
})

export default ListPage
